from django.contrib.auth import login, authenticate, logout
from django.contrib.auth.mixins import LoginRequiredMixin
from django.http import JsonResponse
from django.shortcuts import render, redirect, reverse
from django.views import View
from django import http
import re
from pymysql import DatabaseError
from django_redis import get_redis_connection

from .models import User
from meiduo_mall.utils.response_code import RETCODE


class UserCenterView(LoginRequiredMixin, View):
    # redirect_field_name = 'aaa'  默认是next

    def get(self, request):
        # if request.user.is_authenticated:
        #     return render(request, 'user_center_info.html')
        # else:
        #     return redirect(reverse("users:login"))
        # 上面不灵活
        # login_url = '/login/'
        return render(request, 'user_center_info.html')


class LogoutView(View):
    def get(self, request):
        logout(request)
        # 清除cookie
        response = redirect(reverse("contents:index"))
        response.delete_cookie("username")  # 登录和注册的时候设置了该cookie
        return response


class LoginView(View):
    def get(self, request):
        return render(request, 'login.html')

    def post(self, request):
        # 接收请求参数
        username = request.POST.get("username")
        password = request.POST.get("password")
        remembered = request.POST.get("remembered")
        # 校验参数
        if not all([username, password]):
            return http.HttpResponseForbidden("缺少必传参数")

        if not re.match(r'^[a-zA-Z0-9_-]{5,20}$', username):
            return http.HttpResponseForbidden("请输入正确的用户名或手机号")
        if not re.match(r'^[0-9A-Za-z]{6,15}$', password):
            return http.HttpResponseForbidden("密码最少6位，最长15位")
        # 认证用户
        # user = User.objects.get(username=username)
        # user.check_password(password)  这两句代码，django已经封装了
        user = authenticate(username=username, password=password)
        if user is None:
            return render(request, 'login.html', {'account_errmsg': '账号或密码错误'})
        # 状态保持
        login(request, user)

        if remembered != 'on':
            # 不记住，浏览器关掉即销毁
            request.session.set_expiry(0)
        else:
            request.session.set_expiry(None)  # None默认两周失效
        # 重定向

        next = request.GET.get('next')  # REDIRECT_FIELD_NAME默认是next

        if next:
            response = redirect(next)
        else:
            response = redirect(reverse("contents:index"))

        response.set_cookie("username", username, max_age=60 * 30)  #

        return response


class RegisterView(View):
    def get(self, request):
        return render(request, 'register.html')

    def post(self, request):
        # 获取表单数据
        username = request.POST.get('username')
        password = request.POST.get('password')
        password2 = request.POST.get('password2')
        mobile = request.POST.get('mobile')
        allow = request.POST.get('allow')
        sms_code_client = request.POST.get("sms_code")

        # 校验是否为空
        if not all([username, password, password2, mobile, allow, sms_code_client]):
            return http.HttpResponseForbidden('必填项不能为空')

        if not re.match(r'^[a-zA-Z0-9-_]{5,20}$', username):
            return http.HttpResponseForbidden('用户名请输入5-20位字符')

        if not re.match(r'^[a-zA-Z0-9-_@*]{6,15}$', password):
            return http.HttpResponseForbidden('密码请输入6-15位字符')
        if not re.match(r'^[a-zA-Z0-9-_@*]{6,15}$', password2):
            return http.HttpResponseForbidden('确认密码请输入6-15位字符')

        if password != password2:
            return http.HttpResponseForbidden('两次密码不一致')
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return http.HttpResponseForbidden('你输入的手机号格式不正确')

        # 校验短信验证码
        redis_conn = get_redis_connection('verify_code')
        sms_code_server = redis_conn.get('sms_' + mobile)
        if sms_code_server is None:
            return render(request, 'register.html', {'register_error': '短信验证码已失效'})
        if sms_code_server.decode() != sms_code_client:
            return render(request, 'register.html', {"register_error": '短信验证码错误'})

        if allow != 'on':
            return http.HttpResponseForbidden('请同意协议')

        try:
            user = User.objects.create_user(username=username, password=password, mobile=mobile)
        except DatabaseError:
            return render(request, 'register.html', {'register_error': '注册失败'})

        # 登录，状态保持
        login(request, user)

        # return redirect('/')
        response = redirect(reverse('contents:index'))
        response.set_cookie("username", user.username, max_age=3600 * 24)  # 将用户名放置cookie中，重定向到首页要用到
        return response


class UsernameView(View):
    def get(self, request, username):
        users = User.objects.filter(username=username)
        count = users.count()
        return JsonResponse({'code': RETCODE.OK, 'msg': 'ok', 'count': count})


class MobileView(View):
    def get(self, request, mobile):
        count = User.objects.filter(mobile=mobile).count()
        return JsonResponse({'code': RETCODE.OK, 'msg': 'ok', 'count': count})
